//
//  XDTodoDetailViewController.m
//  iphone.mobileoa
//
//  Created by 李亚春 on 13-6-3.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "XDTodoDetailViewController.h"
#import "Handle_GetWaitHandleDetail_Task.h"
#import "FlowInfoModel.h"
#import "XDFlowInfoCell.h"
#import "XDAttachCell.h"
#import "MaterialModel.h"
#import "DBFrameService.h"
#import "CommonUtil.h"
#import "AttachDownloadTask.h"
#import "OperationInfoModel.h"
#import "TSActionSheet.h"
#import "XDNextStepViewController.h"
#import "ActivityInfoModel.h"
#import "TargetActivityInfoModel.h"

@interface XDTodoDetailViewController ()
{
    NSString *FileType,*MessageItemGuid,*getDetailTaskGuid;
    NSMutableArray *flowInfoDataArray,*attachDataArray;
    int selectedIndex;
    NSString *downloadtaskguid;
    NSMutableArray *operationList;
    ActivityInfoModel *activityInfoModel;
    PopoverView *pv;
    OperationInfoModel *fz30oim;
}
@end

@implementation XDTodoDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"待办详情";
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"操作" style:UIBarButtonItemStyleBordered target:self action:@selector(showActionSheet:forEvent:)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    [self.tabBar setDelegate:self];
    FileType = [intentParams objectForKey:@"FileType"];
    MessageItemGuid = [intentParams objectForKey:@"MessageItemGuid"];
    NSMutableDictionary *params = self.getPassDictionary;
    [params setObject:MessageItemGuid forKey:@"MessageItemGuid"];
    
    [self showMBPHUD];
    getDetailTaskGuid = [[[Handle_GetWaitHandleDetail_Task alloc]initWithContext:self andParams:params]startTask];
    
    [self.tabBar setSelectedItem:self.tabBarBd];
    
    
    //    NSString *path = [[NSBundle mainBundle]pathForResource:@"IncreaseZoomFactor" ofType:@"js"];
    //
    //    NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //
    //    [self.wv stringByEvaluatingJavaScriptFromString:jsCode];
    //
    //    [self.wv stringByEvaluatingJavaScriptFromString:@"increaseMaxZoomFactor()"];
    
    self.wv.scalesPageToFit = YES;
}

-(void)showActionSheet:(id)sender forEvent:(UIEvent*)event
{
    TSActionSheet *actionSheet = [[TSActionSheet alloc] initWithTitle:@"下一步操作"];
    for (int i=0; i<operationList.count; i++) {
        OperationInfoModel *oim = [operationList objectAtIndex:i];
        
        
        [actionSheet addButtonWithTitle:oim.OperationName block:^{
            //    按钮类型，shift表示转交，back表示退回，pass表示送下一步
            if([oim.OperationType isEqualToString:@"shift"]){
                
                
                //                [param setObject:@"shift" forKey:@"OperationType"];
                
                NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
                [param setObject:activityInfoModel forKey:@"activityInfoModel"];
                [param setObject:oim forKey:@"OperationInfoModel"];
                [param setObject:MessageItemGuid forKey:@"MessageItemGuid"];
                [param setObject:[intentParams objectForKey:@"listContext"] forKey:@"listContext"];
                XDNextStepViewController *vc = [[XDNextStepViewController alloc]initWithParams:param];
                [self.navigationController pushViewController:vc animated:YES];
                return ;
                
            }else if([oim.OperationType isEqualToString:@"back"]){
                //        [param setObject:@"back" forKey:@"OperationType"];
            }else if([oim.OperationType isEqualToString:@"pass"]||[@"pass_transition" isEqualToString:oim.OperationType]){
                
                if([oim.IsSongPY isEqualToString:@"1"])
                {
                    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
                    [param setObject:activityInfoModel forKey:@"activityInfoModel"];
                    [param setObject:oim forKey:@"OperationInfoModel"];
                    [param setObject:MessageItemGuid forKey:@"MessageItemGuid"];
                    [param setObject:[intentParams objectForKey:@"listContext"] forKey:@"listContext"];
                    XDNextStepViewController *vc = [[XDNextStepViewController alloc]initWithParams:param];
                    [self.navigationController pushViewController:vc animated:YES];
                    return ;
                }
                
                if ([activityInfoModel.SplitType isEqualToString:@"10"]) {
                    
                    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
                    [param setObject:activityInfoModel forKey:@"activityInfoModel"];
                    [param setObject:oim forKey:@"OperationInfoModel"];
                    [param setObject:MessageItemGuid forKey:@"MessageItemGuid"];
                    [param setObject:[intentParams objectForKey:@"listContext"] forKey:@"listContext"];
                    [param setObject:@"0" forKey:@"fz10"];
                    XDNextStepViewController *vc = [[XDNextStepViewController alloc]initWithParams:param];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                else //if(activityInfoModel.SplitType isEqualToString:@"30")
                {
                    if (oim.TargetActivityList.count==1) {
                        NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
                        [param setObject:activityInfoModel forKey:@"activityInfoModel"];
                        [param setObject:oim forKey:@"OperationInfoModel"];
                        [param setObject:MessageItemGuid forKey:@"MessageItemGuid"];
                        [param setObject:[intentParams objectForKey:@"listContext"] forKey:@"listContext"];
                        [param setObject:@"0" forKey:@"fz30"];
                        XDNextStepViewController *vc = [[XDNextStepViewController alloc]initWithParams:param];
                        [self.navigationController pushViewController:vc animated:YES];
                        return ;
                    }
                    
                    fz30oim = oim;
                    NSMutableArray *arr = [[NSMutableArray alloc]init];
                    for (int j=0;j<oim.TargetActivityList.count;j++) {
                        TargetActivityInfoModel *tm = [oim.TargetActivityList objectAtIndex:j];
                        [arr addObject:tm.ActivityName];
                    }
                    
                    CGPoint cp = CGPointMake(290, -5);
                    
                    pv = [PopoverView showPopoverAtPoint:cp
                                                  inView:self.view
                                               withTitle:@"请选择分支活动"
                                         withStringArray:arr
                                                delegate:self];
                }
            }
            
        }];
    }
    
    actionSheet.cornerRadius = 2;
    [actionSheet showWithTouch:event];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    //Dispose of any resources that can be recreated.
}

#pragma controller

-(void)refreshUIWithThreadGuid:(NSString *)threadGuid andData:(NSObject *)obj
{
    [self hideMBPHUD];
    
    if ([getDetailTaskGuid isEqualToString:threadGuid]) {
        NSString *bs = (NSString *)obj;
        
        NSLog(@"%@",bs);
        
        if ([self validateXML:bs]) {
            NSString *formUrl = [StringUtil getXMLFormatedAttribute:bs :@"FormShowUrl"];
            NSURL *url = [NSURL URLWithString:formUrl];
            NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
                                                      cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                  timeoutInterval:60.0];
            [self.wv loadRequest:theRequest];
            
            flowInfoDataArray = [[Handle_GetWaitHandleDetail_Task getFlowInfoDataArray:bs]retain];
            attachDataArray = [[Handle_GetWaitHandleDetail_Task getMeterialDataArray:bs]retain];
            [self.tvBZ reloadData];
            [self.tvFj reloadData];
            
            self.tabBarFj.badgeValue = [NSString stringWithFormat:@"%i",attachDataArray.count];
            
            operationList = [[Handle_GetWaitHandleDetail_Task getOperationInfoDataArray:bs]retain];
            
            activityInfoModel = [[ActivityInfoModel alloc]init];
            activityInfoModel.ActivityGuid = [[StringUtil getXMLFormatedAttribute:bs :@"ActivityGuid"]retain];
            activityInfoModel.ActivityName = [[StringUtil getXMLFormatedAttribute:bs :@"ActivityName"]retain];
            activityInfoModel.ActivityDispName = [[StringUtil getXMLFormatedAttribute:bs :@"ActivityDispName"]retain];
            activityInfoModel.SplitType = [[StringUtil getXMLFormatedAttribute:bs :@"SplitType"]retain];
            activityInfoModel.ApplicationConfig = [[StringUtil getXMLFormatedAttribute:bs :@"ApplicationConfig"]retain];
            activityInfoModel.Note = [[StringUtil getXMLFormatedAttribute:bs :@"Note"]retain];
            
            
        }
    }
    else if([downloadtaskguid isEqualToString:threadGuid])
    {
        NSString *bs = (NSString *)obj;
        [self openFileFromSecondApp:bs];
    }
}

-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    if (item.tag==2001) {
        self.wv.hidden = NO;
        self.tvBZ.hidden = YES;
        self.tvFj.hidden = YES;
        selectedIndex = 0;
    }
    else if (item.tag==2002) {
        self.tvBZ.hidden = NO;
        self.wv.hidden = YES;
        self.tvFj.hidden = YES;
        selectedIndex = 1;
        [self.tvBZ reloadData];
    }
    else if (item.tag==2003) {
        self.tvBZ.hidden = YES;
        self.wv.hidden = YES;
        self.tvFj.hidden = NO;
        selectedIndex = 2;
        [self.tvFj reloadData];
    }
}

- (void)dealloc {
    [_wv release];
    [_tabBar release];
    [_tvBZ release];
    [_tvFj release];
    [_tabBarFj release];
    [_tabBarBd release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setWv:nil];
    [self setTabBar:nil];
    [self setTvBZ:nil];
    [self setTvFj:nil];
    [self setTabBarFj:nil];
    [self setTabBarBd:nil];
    [super viewDidUnload];
}

#pragma tableview

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (selectedIndex==1) {
        static NSString *identifier = @"XDFlowInfoCell";
        XDFlowInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"XDFlowInfoCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        
        FlowInfoModel *m = [flowInfoDataArray objectAtIndex:indexPath.row];
        cell.lbBz.text = [NSString stringWithFormat:@"步骤：%@",m.ActivityName];
        cell.lbBlr.text = [NSString stringWithFormat:@"办理人：%@",m.HandleUserName];
        cell.lbCz.text = [NSString stringWithFormat:@"操作：%@",m.HandleUserName];
        cell.lbSdsj.text = [NSString stringWithFormat:@"收到时间：%@",m.ReceiveDateTime];
        cell.lbClsj.text = [NSString stringWithFormat:@"处理时间：%@",m.HandleDateTime];
        cell.lbBlyj.text = [NSString stringWithFormat:@"处理意见：%@",m.Opinion];
        return cell;
    }
    else if(selectedIndex==2)
    {
        static NSString *identifier = @"XDFlowInfoCell";
        XDAttachCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"XDAttachCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        
        MaterialModel *m = [attachDataArray objectAtIndex:indexPath.row];
        cell.lbAttachName.text = m.MaterialInstanceName;
        return cell;
    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (selectedIndex==1) {
        return flowInfoDataArray.count;
    }
    else if (selectedIndex==2) {
        return attachDataArray.count;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (selectedIndex==1) {
        return 84;
    }
    else if(selectedIndex==2)
    {
        return 44;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (selectedIndex==2) {
        MaterialModel *m = [attachDataArray objectAtIndex:indexPath.row];
        if ([m.isBigFile isEqualToString:@"1"]) {
            [UITool toast:@"大附件无法下载！"];
            return;
        }
        
        NSString *savePath = [NSString stringWithFormat:@"%@/Documents/attaches/%@/%@",NSHomeDirectory(),MessageItemGuid,m.MaterialInstanceName];
        NSString *downloadurl = [[CommonUtil getDownloadUrl:m.DownLoadUrl]retain];
        NSMutableDictionary *params = self.getPassDictionary;
        [params setObject:savePath forKey:@"savePath"];
        [params setObject:downloadurl forKey:@"url"];
        [params setObject:MessageItemGuid forKey:@"folerguid"];
        [self showMBPHUD];
        downloadtaskguid = [[[AttachDownloadTask alloc]initWithContext:self andParams:params]startTask];
    }
}

-(void)popoverView:(PopoverView *)popoverView didSelectItemAtIndex:(NSInteger)index
{
    [popoverView dismiss:YES];
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:activityInfoModel forKey:@"activityInfoModel"];
    [param setObject:fz30oim forKey:@"OperationInfoModel"];
    [param setObject:MessageItemGuid forKey:@"MessageItemGuid"];
    [param setObject:[intentParams objectForKey:@"listContext"] forKey:@"listContext"];
    [param setObject:[NSString stringWithFormat:@"%i",index] forKey:@"fz30"];
    XDNextStepViewController *vc = [[XDNextStepViewController alloc]initWithParams:param];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
